package com.web;

import com.pojo.Cart;
import com.pojo.Order;
import com.pojo.OrderItem;
import com.pojo.User;
import com.service.OrderService;
import com.service.impl.OrderServiceImpl;
import com.uitl.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class OrderServlet extends BaseServlet{
    OrderService orderService = new OrderServiceImpl();

    //生成订单
    protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //调用OrderService.createOrder(Cart,UserId);所以需要获取两个参数
        //获取Cart购物车对象
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        //获取userID
        User loginUser = (User) req.getSession().getAttribute("user");
        if (loginUser ==null){
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);//如果没有登录，就跳转到登录页面
            return;//后面不需要再执行
        }

        Integer userid = loginUser.getId();

        //生成订单
        String orderId = orderService.createOrder(cart, userid);

        req.getSession().setAttribute("orderId",orderId);

//        req.getRequestDispatcher("/pages/cart/checkout.jsp").forward(req,resp);
        resp.sendRedirect(req.getContextPath()+"/pages/cart/checkout.jsp");
    }


    protected void showMyOrders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取userID
        User loginUser = (User) req.getSession().getAttribute("user");
        if (loginUser ==null){
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);//如果没有登录，就跳转到登录页面
            return;//后面不需要再执行
        }
        Integer userid = loginUser.getId();
        List<Order> orders = orderService.showMyOrders(userid);
        req.getSession().setAttribute("orders",orders);
        resp.sendRedirect(req.getContextPath()+"/pages/manager/order_manager.jsp");
    }

    //订单详情页
    protected void showOrderItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String orderId = req.getParameter("orderId");
        List listForOrderItems = orderService.showOrderItem(orderId);

        req.getSession().setAttribute("listForOrderItems",listForOrderItems);
        req.getSession().setAttribute("orderId",orderId);
        resp.sendRedirect(req.getContextPath()+"/pages/manager/orderItem_manager.jsp");
    }
}
